<?php
namespace app\gr\BLL;

use app\common\BLL\Repository;
use think\Db;

class CardRedeemBLL extends Repository
{
    public function model()
    {
        return 'CardRedeem';
    }

    public function getbyid($id,$columns="*"){
        $info = $this->model
                    ->alias('a')
                    ->join('gr_card_pub pub','a.pub_id=pub.id')
                    ->join('gr_card_type type','pub.card_id=type.id')
                    ->field($columns)
                    ->where('a.id',$id)
                    ->find();
        return $info;
    }

    public function getList($where=[]){
        $list = $this->model
                    ->alias('a')
                    ->join('gr_card_pub pub','a.pub_id=pub.id')
                    ->join('gr_card_type type','pub.card_id=type.id')
                    ->field('type.name tpname,type.spk,a.*')
                    ->where($where)
                    ->select();
        return $list;
    } 

    public function getListPage($where=[],$row=10){
        $list = $this->model
            ->alias('a')
            ->join('gr_card_pub pub','a.pub_id=pub.id')
            ->join('gr_card_type type','pub.card_id=type.id')
            ->field('type.name tpname,type.spk,pub.card_no,pub.card_psd,a.*')
            ->where($where)
            ->paginate($row);
                    
        return $list;

    }

    public function create(array $attributes){
        //检查错误
        $cardPubBLL = new CardPubBLL();

        $pubInfo = $cardPubBLL->getbyid($attributes['pub_id']);
        if($pubInfo['status'] != 1 
            || $pubInfo['card_no']!=$attributes['no']
            || $pubInfo['card_psd']!=$attributes['psd']){
            return array('status'=> 0,'msg'=>'信息验证失败');
        }
        
        Db::startTrans();
        try {
            //更新状态
            $cardPubBLL->update(array('status'=>2),$attributes['pub_id']);
            //写入数据
            parent::create($attributes);
            // 提交事务
            Db::commit();
            return array('status' => 1, 'msg' => '更新成功');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            return array('status' => 0, 'msg' => '更新失败');
        }

    }
}
